
/**
 * Module dependencies.
 */

var express = require('express'),
	mongoose = require('mongoose');

var Schema = mongoose.Schema
  , ObjectId = Schema.ObjectId
  , db = mongoose.connect('mongodb://localhost/test');


//mongoose.connect('mongodb://localhost/test');

var app = module.exports = express.createServer();

var num_coffees = 0, total_amount = 0, spent_total = 0, balance = 0;


// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 
});

app.configure('production', function(){
  app.use(express.errorHandler()); 
});

//DB Stuff
var JcSchema = new Schema({
    user     : String
  , amount      : Number
  , message      : String
});
// middleware
JcSchema.pre('save', function (next) {
    console.log("Save is called!" + this.get('user') + ", amount : " + this.get('amount'));
    next();
});

var JcModel = mongoose.model('JcModel', JcSchema);


// Routes

app.get('/', function(req, res){
	
	JcModel.find({}, function (err, docs) {

	res.render('index', {
    	title: 'Jonathan Mock Coffee Card',
 		num_coffees: num_coffees,
		total_amount: total_amount,
		spent_total: spent_total,
		balance: balance,
		docs: docs
  	});
  

	});
	
	
	
//locals: { name: 'tj', email: 'tj@vision-media.ca' }

});

var cost_per_item = 5;

app.get('/buy', function(req, res){
  res.render('buy', {
    title: 'Buy coffee, it is free dude!'
  });
});


app.get('/give', function(req, res){
  res.render('give', {
    title: 'OK, you want to give someone a coffee!!'
  });
});

function saveRow(name, message, amount) {
	var row = new JcModel();
	row.user = name;
	row.message = message;
	row.amount = amount;
	row.save(function (err) {
	  if (!err) console.log('Success saving entry in mongo!');
	  
	  tweet("#html5jc -- " + message);
	
	});
}


function tweet(message) {
	var key = 'FSfiDXvJFdnZq1HvdCn8WQ',
	 	secret='1EnZ8eqeEsEmptQMnxGwjb7VpegIPGAyj8r2lTLP3fg',
		oauth_token='YOUR-AUTH-TOKEN-HERE',
		oauth_token_secret='YOUR-AUTH-TOKEN-SECRET-HERE';

	var twitterClient = require('twitter-js')(key, secret);
		
	twitterClient.apiCall('POST', '/statuses/update.json',
		{token: {oauth_token_secret: oauth_token_secret, oauth_token: oauth_token}, status: message},
        function (error, result) {
//		  console.log('error - ' + JSON.stringify(error));
//		  console.log('result - ' + result);
		  console.log('Success tweeting');
	    }
	  );

	
}
app.post('/buy', function(req, res){
//	console.log("Request post data - " + req.body.user.name);
//	console.log("Request post data - " + req.body.user.message);
//	console.log("Request post data - " + req.body.user.amount);

  num_coffees++;
  total_amount -= cost_per_item;
  spent_total += cost_per_item;
  balance -= cost_per_item;

  saveRow(req.body.user.name, req.body.user.message, -cost_per_item);
	
	res.redirect('/');
});


app.post('/give', function(req, res){
	var value = parseInt(req.body.user.amount);
  total_amount += value;
  balance += value;

//	console.log("Request post data - " + req.body.user.name);
//	console.log("Request post data - " + req.body.user.message);
//	console.log("Request post data - " + req.body.user.amount);

  saveRow(req.body.user.name, req.body.user.message, req.body.user.amount);
	res.redirect('/');

});


app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
